<?php

/**
 * 类名：Mongo
 * 作者：mqycn
 * 博客：http://www.miaoqiyuan.cn
 * 源码：https://gitee.com/mqycn/ShortUrl
 * 说明：Mongo存储类
 */
namespace drivers;

require_once __DIR__ . '/core/Driver.php';

use drivers\core\Driver;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query;

class Mongo extends Driver {

	private $manager;
	private $database;

	public function __construct($config = ['server' => "mongodb://localhost:27017", 'db' => 'test']) {
		$this->database = $config['db'];
		$this->manager = new Manager($config['server']);
	}

	//插入记录
	public function insert($table, $data, $features = []) {
		$bulk = new BulkWrite;
		$bulk->insert($data);
		$this->manager->executeBulkWrite($this->table($table), $bulk);
	}

	//查询记录
	protected function query($table, $where = [], $sort = [], $features = []) {
		$options = [];
		if (!empty($sort)) {
			$options['sort'] = $sort;
		}
		if (!empty($features['projection'])) {
			$options['projection'] = $features['projection'];
		}
		$query = new Query($where, $options);
		$result = $this->manager->executeQuery($this->table($table), $query)->toArray();
		if (!empty($result)) {
			$data = [];
			foreach ($result as $row) {
				$item = [];
				foreach ($row as $key => $val) {
					$item[$key] = $val;
				}
				$data[] = $item;
			}
			$result = $data;
		}
		return $result;
	}

	//更新记录
	protected function update($table, $where, $data, $features = []) {
		$bulk = new BulkWrite;
		$bulk->update($where, ['$set' => $data]);
		$this->manager->executeBulkWrite($this->table($table), $bulk);
	}

	//返回集合名
	private function table($table) {
		return $this->database . '.' . $table;
	}

}
